package cn.lh.interceptor;

import cn.lh.contants.ErrorCode;
import cn.lh.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * @描述:
 * @版权: Copyright (c) 2023
 * @作者: linhong
 * @版本: 1.0.0
 * @创建时间: 2023/12/28
 */
@Slf4j
public class MyInterceptor implements HandlerInterceptor {

    @Resource
    private RedisTemplate redisTemplate;




    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        String requestURL = request.getRequestURL().toString();
        String method = request.getMethod();
        if(method.equals("OPTIONS")){
            return true;
        }else{
            String token = request.getHeader("authorization");
            if(StringUtils.isBlank(token) || !redisTemplate.hasKey(token)){
                log.info("未登录或登录失效");
                log.info("requestURL:" +requestURL);
                response.setStatus(401);
                return false;
            } else{
                redisTemplate.expire(token,120, TimeUnit.MINUTES);
            }
        }
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("request : {}, response : {}",request,response);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
